package org.zavgame.rest;

import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

/**
 * Coins service bootstrap class.
 * Initialize the InitialContext.
 * 
 * @author alexey
 *
 */
public class CoinsServiceBootstrap implements ServletContextListener
{
   static final String COINS_INITIAL_CONTEXT = CoinsInitialContext.class.getName();
   
   private static final Logger LOG = Logger.getLogger(CoinsServiceBootstrap.class.getName());

   /**
    * Initialize the InitialContext.
    */
   public void contextInitialized(ServletContextEvent sce)
   {
      ServletContext sctx = sce.getServletContext();
      CoinsInitialContext coinsInitialContext = new CoinsInitialContext();
      if (sctx != null)
      {
         Properties p = new Properties();
         if (sctx.getInitParameter("java.naming.factory.initial") != null)
         {
            p.put("java.naming.factory.initial", sctx.getInitParameter("java.naming.factory.initial"));
         }
         if (sctx.getInitParameter("java.naming.provider.url") != null)
         {
            p.put("java.naming.provider.url", sctx.getInitParameter("java.naming.provider.url"));
         }
         // user and pass optional
         if (sctx.getInitParameter("java.naming.security.principal") != null)
         {
            p.put("java.naming.security.principal", sctx.getInitParameter("java.naming.security.principal"));
         }
         if (sctx.getInitParameter("java.naming.security.credentials") != null)
         {
            p.put("java.naming.security.credentials", sctx.getInitParameter("java.naming.security.credentials"));
         }
         try
         {
            InitialContext ctx = new InitialContext(p);
            coinsInitialContext.setContext(ctx);
            sctx.setAttribute(COINS_INITIAL_CONTEXT, coinsInitialContext);
         }
         catch (NamingException e)
         {
            LOG.error("Can't instantiate the initial context", e);
         }
      }
   }

   /**
    * Runs once on context destroyed.
    */
   public void contextDestroyed(ServletContextEvent sce)
   {
      ServletContext sctx = sce.getServletContext();
      sctx.removeAttribute(COINS_INITIAL_CONTEXT);
   }

}
